package com.jiamao.goplay.ui.user.vm;

import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.databinding.ObservableList;

import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.res.ResMatch;
import com.jiamao.goplay.bean.res.ResUserInfoDetail;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.AddrDetailFragment;
import com.jiamao.goplay.ui.discover.MatchFragment;
import com.jiamao.goplay.ui.discover.vm.FindItemImageViewVM;
import com.jiamao.goplay.ui.user.UserOtherWantGoToFragment;
import com.jiamao.goplay.util.GsonUtil;
import com.netease.nim.uikit.business.team.viewholder.TeamAnnounceHolder;
import com.tamsiree.rxkit.view.RxToast;

import java.io.Serializable;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;

public class UserOtherInfoVM extends BaseViewModel<DataRepository> {


    //用户名的绑定
    public ObservableField<String> userName = new ObservableField<>("");
    public ObservableField<String> age = new ObservableField<>("");
    public ObservableField<String> location = new ObservableField<>("");

    public ObservableField<String> imgUrl = new ObservableField<>("");

    public ObservableField<String> gotoNumDec = new ObservableField<>("我想去的（0）");


    public ObservableField<String> sz = new ObservableField<>("");
    public ObservableField<String> sg = new ObservableField<>("");
    public ObservableField<String> tz = new ObservableField<>("");
    public ObservableField<String> hy = new ObservableField<>("");
    public ObservableField<String> zw = new ObservableField<>("");
    public ObservableField<String> dx = new ObservableField<>("");
    public ObservableField<String> gs = new ObservableField<>("");
    public ObservableField<String> ah = new ObservableField<>("");
    public ObservableField<String> des = new ObservableField<>("添加关于我，可以获得更多的邀请和回复.....");
    public ObservableField<String> id = new ObservableField<>("0");

    public ObservableField<Integer> isVip = new ObservableField<>();

    public ObservableField<Integer> isShming = new ObservableField<>();
    public ObservableField<Integer> isRenXiang = new ObservableField<>();



    public ObservableInt desVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt zlBtnVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt sgBtnVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt tzBtnVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt hyBtnVisibility = new ObservableInt(View.VISIBLE);

    public ObservableInt zwBtnVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt dxBtnVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt gsBtnVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt ahBtnVisibility = new ObservableInt(View.VISIBLE);


    public ObservableField<String> goto_status = new ObservableField<>("");
    public ObservableField<String> goto_city = new ObservableField<>("");
    public ObservableField<String> goto_nums = new ObservableField<>("");
    public ObservableField<String> goto_img = new ObservableField<>("");
    public ObservableInt yqBtnVisibility = new ObservableInt(View.GONE);
    public ObservableInt yyqBtnVisibility = new ObservableInt(View.GONE);
    public ObservableInt ypdBtnVisibility = new ObservableInt(View.GONE);
    public ObservableInt jsyqBtnVisibility = new ObservableInt(View.GONE);

    public ObservableInt gotoBtnVisibility = new ObservableInt(View.GONE);


    private String uid;
    private int sex;

    private String pid,plcid;

    //封装一个界面发生改变的观察者
    public UserOtherInfoVM.UIChangeObservable uc = new UserOtherInfoVM.UIChangeObservable();

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<String> pSwitchEvent = new SingleLiveEvent<>();

        public SingleLiveEvent<Integer> refMaxNum = new SingleLiveEvent<>();

        public SingleLiveEvent<Integer> uiInitRefreshEvent = new SingleLiveEvent<>();

        public SingleLiveEvent<String> startChat = new SingleLiveEvent<>();
    }

    public UserOtherInfoVM(@NonNull Application application, DataRepository repository) {
        super(application, repository);
    }
    //登录按钮的点击事件


    //登录按钮的点击事件
    public BindingCommand backOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
                 finish();
        }
    });

    //登录按钮的点击事件
    public BindingCommand moreClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
           // finish();
        }
    });


    //登录按钮的点击事件
    public BindingCommand gotoCliCk = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            // finish();
            Bundle bd = new Bundle();
            bd.putString("uid",uid);
            bd.putInt("sex",sex);
            startContainerActivity(UserOtherWantGoToFragment.class.getCanonicalName(),bd);
        }
    });




    //登录按钮的点击事件
    public BindingCommand moreAdd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            finish();
        }
    });

    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableListImage = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBindingImage = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();

            //设置头布局
            itemBinding.set(BR.viewModel, R.layout.discover_find_item_viewpage_image_layout);


        }
    });


    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
                itemBinding.set(BR.viewModel, R.layout.user_other_goto_addr_item_layout);
            // itemBinding.set(BR.viewModel, R.layout.msg_home_item_layout);

        }
    });

    public void updateUserInfo(ResUserInfoDetail info){

        if (info.getCertification()!=null){
            isVip.set(info.getCertification().getIsVip() == 0? View.GONE:View.VISIBLE);
            isRenXiang.set(info.getCertification().getAvatarVerified() == 0? View.GONE:View.VISIBLE);
            isShming.set(info.getCertification().getRealNameVerified() == 0? View.GONE:View.VISIBLE);
        }
        if (info.getBaseInfo()!=null){
            uid = info.getBaseInfo().getId();
            sex = info.getBaseInfo().getGender();
            uc.pSwitchEvent.setValue(info.getBaseInfo().getNickname());
            //  uc.pRenxiangEvent.setValue(info.getCertification().getAvatarVerified());

            userName.set( info.getBaseInfo().getNickname());

            imgUrl.set( info.getBaseInfo().getAvatar());
            id.set(info.getBaseInfo().getId()+"");

            // phoneNum.set(info.getAvatarList().size()+"/6");
            // gotoNum.set(info.getPlaceWantGo().size()+"");
            // paifNum.set(info.getInviteInfo().getMatchNum()+"");
//        invNum.set(info.getInviteInfo().getInviteMyNum()+"");
            String sexa = info.getBaseInfo().getGender()==1?"男":"女";

            age.set(  sexa+" / "+info.getUserInfo().getAge()+" / "+info.getUserInfo().getGalaxy());
        }

        if (info.getLocation()!=null){
            location.set(info.getLocation().getDistance()+"km，"+info.getLocation().getCity()+"，"+info.getLocation().getArea()+", "+info.getBaseInfo().getIsActive());
        }

        if (info.getUserInfo() == null){
            desVisibility.set(View.GONE);
            zlBtnVisibility.set(View.GONE);
        }
        if (TextUtils.isEmpty(info.getUserInfo().getHeight()) && TextUtils.isEmpty(info.getUserInfo().getWeight()) && TextUtils.isEmpty(info.getUserInfo().getIndustry())
                && TextUtils.isEmpty(info.getUserInfo().getPosition()) && TextUtils.isEmpty(info.getUserInfo().getUniversity())
                && TextUtils.isEmpty(info.getUserInfo().getInterest()) && TextUtils.isEmpty(info.getUserInfo().getCompany())){
            zlBtnVisibility.set(View.GONE);
        }


        if (TextUtils.isEmpty(info.getUserInfo().getDescribe())){
            desVisibility.set(View.GONE);
        }

        if (TextUtils.isEmpty(info.getUserInfo().getHeight())){
            sgBtnVisibility.set(View.GONE);
        }

        if (TextUtils.isEmpty(info.getUserInfo().getWeight())){
            tzBtnVisibility.set(View.GONE);
        }
        if (TextUtils.isEmpty(info.getUserInfo().getIndustry())){
            hyBtnVisibility.set(View.GONE);
        }
        if (TextUtils.isEmpty(info.getUserInfo().getPosition())){
            zwBtnVisibility.set(View.GONE);
        }
        if (TextUtils.isEmpty(info.getUserInfo().getUniversity())){
            dxBtnVisibility.set(View.GONE);
        }
        if (TextUtils.isEmpty(info.getUserInfo().getCompany())){
            gsBtnVisibility.set(View.GONE);
        }
        if (TextUtils.isEmpty(info.getUserInfo().getInterest())){
            ahBtnVisibility.set(View.GONE);
        }




        if (info.getUserInfo() !=null){
            sz.set(info.getUserInfo().getGalaxy());
            sg.set(info.getUserInfo().getHeight());
            tz.set(info.getUserInfo().getWeight());
            hy.set(info.getUserInfo().getIndustry());
            zw.set(info.getUserInfo().getPosition());
            dx.set(info.getUserInfo().getUniversity());
            ah.set(info.getUserInfo().getInterest());
            des.set(info.getUserInfo().getDescribe());
            gs.set(info.getUserInfo().getCompany());
        }

        if (info.getPlaceWantGo()!=null){
            String sex = info.getBaseInfo().getGender() == 1?"他":"她";
            gotoNumDec.set(sex+"想去的（"+info.getPlaceWantGo().size()+"）");
            for (int i=0;i<info.getPlaceWantGo().size();i++){
                UserOtherGotoItemVM item = new UserOtherGotoItemVM(this,  uid, info.getPlaceWantGo().get(i),info.getBaseInfo().getGender());
                item.multiItemType("image");
                observableList.add(item) ;

            }
        }

        if (info.getAvatarList()!=null){
            uc.refMaxNum.setValue(info.getAvatarList().size());
            for (int i=0;i<info.getAvatarList().size();i++){
                MultiItemViewModel itemPhone= new FindItemImageViewVM(this,info.getAvatarList().get(i).getUrl(),null);
                itemPhone.multiItemType("image");
                observableListImage.add(itemPhone) ;
            }

        }



        if (info.getRelationPlace() == null){
            gotoBtnVisibility.set(View.GONE);
        }

        if (SPUtils.getInstance().getString(Config.UID).equals(uid)){
            gotoBtnVisibility.set(View.GONE);
        }

        if (info.getRelationPlace()!=null){

            goto_img.set(info.getRelationPlace().getPlaceCover());
            goto_city.set(info.getRelationPlace().getCity());
            goto_nums.set(info.getRelationPlace().getInterestUserNum()+"人想去");
            goto_status.set(info.getRelationPlace().getStatusDes());
            pid = info.getRelationPlace().getInvID();
            plcid = info.getRelationPlace().getPlaceId();
            switch (info.getRelationPlace().getStatus()){
                case 0:
                    gotoBtnVisibility.set(View.GONE);
                    break;
                case 1:
                    jsyqBtnVisibility.set(View.VISIBLE);
                    gotoBtnVisibility.set(View.VISIBLE);
                    break;
                case 2:
                    ypdBtnVisibility.set(View.VISIBLE);
                    gotoBtnVisibility.set(View.VISIBLE);
                    break;
                case 3:
                    yyqBtnVisibility.set(View.VISIBLE);
                    gotoBtnVisibility.set(View.VISIBLE);
                    break;
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void getLoadInitData(String uid) {
        //uc.pSwitchEvent.setValue();
        //String uid = SPUtils.getInstance().getString(Config.UID)+"";
        Log.d("HTML","UID:"+uid);
        model.getApi().getOtherUserInfo(uid)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        uc.uiInitRefreshEvent.setValue(1);
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResUserInfoDetail>>() {
                    @Override
                    public void onNext(BaseRep<ResUserInfoDetail> baseRep) {

                        super.onNext(baseRep);
                        //保存账号密码
                        if (baseRep.isOk()){
                            uc.uiInitRefreshEvent.setValue(0);
                            updateUserInfo(baseRep.getData());
                        }else {
                            uc.uiInitRefreshEvent.setValue(3);
                            RxToast.showToastShort(baseRep.getMsg());
//
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.d("11111111111111111111111111111111111111111111");
                        uc.uiInitRefreshEvent.postValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {

                    }

                });

    }



    public void yaoqing(String id,UserOtherGotoItemVM vm){
        //uc.pSwitchEvent.setValue();
        model.getApi().invitingHe(id,uid)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep>() {
                    @Override
                    public void onNext(BaseRep baseRep) {

                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            vm.yqBtnVisibility.set(View.GONE);
                            vm.yqnBtnVisibility.set(View.GONE);
                            vm.yyqBtnVisibility.set(View.VISIBLE);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }


    public void jieshouyaoqing(String ids,UserOtherGotoItemVM vm){
        //uc.pSwitchEvent.setValue();
        model.getApi().acceptInvite(ids)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResMatch>>() {
                    @Override
                    public void onNext(BaseRep<ResMatch> baseRep) {

                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            vm.yyqBtnVisibility.set(View.GONE);
                            vm.ypdBtnVisibility.set(View.VISIBLE);
                        //    vm.yyqBtnVisibility.set(View.VISIBLE);

                            Bundle bd= new Bundle();
                            bd.putString("data", GsonUtil.toJson(baseRep.getData()));
                            startContainerActivity(MatchFragment.class.getCanonicalName(),bd);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }
    public void startChat(String id){
        //uc.pSwitchEvent.setValue();
        uc.startChat.setValue(id);

    }




    //条目的点击事件
    public BindingCommand jsyqClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            jieshouyaoqings(pid);
            // ((AddrDetailVM)viewModel).jieshouyaoqing(uid);
        }
    });


    //条目的点击事件
    public BindingCommand yqClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            Bundle bundle = new Bundle();
            bundle.putString("id",plcid);
            startContainerActivity(AddrDetailFragment.class.getCanonicalName(), bundle);


        }
    });
    //条目的点击事件
    public BindingCommand ypdClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startChat(uid);
            //    ((AddrDetailVM)viewModel).yaoqing(uid);
            // viewModel.startContainerActivity(SearchFragment.class.getCanonicalName());
        }
    });


    public void jieshouyaoqings(String ids){
        //uc.pSwitchEvent.setValue();
        model.getApi().acceptInvite(ids)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResMatch>>() {
                    @Override
                    public void onNext(BaseRep<ResMatch> baseRep) {

                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            yyqBtnVisibility.set(View.GONE);
                            ypdBtnVisibility.set(View.VISIBLE);
                            //    vm.yyqBtnVisibility.set(View.VISIBLE);
                            Bundle bd= new Bundle();
                            bd.putString("data", GsonUtil.toJson(baseRep.getData()));
                            startContainerActivity(MatchFragment.class.getCanonicalName(),bd);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }

}
